/*******************************************************************************
 * Fotogallery creata con jQuery.
 * Plugin jQuery.
 * 
 * @author      Mattia Leonardo Angelillo
 * @email       mattia.angelillo@gmail.com
 * @date        06/12/2014
 * @version     1.2.0
 * @description Possibilità di creare una galleria fotografica selezionando
 *              le foto dagli album di Picasa.
 *              Nel caso si usi il menu con Picasa si richiamano tutti gli 
 *              album dell'account inserito e cliccando su uno di essi si 
 *              esegue l'album selezionato.
 *              Se in modalità fullscreen è in grado di adattarsi automaticamente
 *              alle dimensioni della pagina.
*******************************************************************************/

(function( $ ) {
    /**=================================================
     * Configurazioni globali
    ==================================================*/
    /*#######################################
     * Variabili contenenti le posizioni
     * degli elementi della photogallery
    #######################################*/
    var container           = "#gioiagallery";
    var container_images    = "#gioiagallery .images";
    var container_image     = "#gioiagallery .images div";
    var container_img_width_this  = null;
    var container_img_height_this = null;
    var container_commands  = "#gioiagallery .commands";
    var container_playpause = "#gioiagallery .commands .playpause";
    var container_play      = "#gioiagallery .commands .play";
    var container_pause     = "#gioiagallery .commands .pause";
    var container_count     = "#gioiagallery .info .count";
    var container_size      = "#gioiagallery .info .total";
    
    var thumbnail           = "#gioiagallery .thumbnail";
    var prev                = "#gioiagallery .commands .prev";
    var next                = "#gioiagallery .commands .next";
    
    var menu                = "#gioiagallery .menu";
    var menu_menu           = "#gioiagallery .menu .menu";
    var menu_toggle         = "#gioiagallery .menu .toggle";
    
    var size                = 0;
    /**
     * Determina se la photogallery è a schermo intero
     * @type Boolean
     */
    var fullscreen          = false;
    var position            = 0;
    /**
     * Contatore per l'autoplay
     * 
     * @type int
     */
    var time                = 0;
    
    /**
     * Verifico se la photogallwery è in play (<b>true</b>)
     * o in pausa (<b>false</b>).
     * 
     * @type Boolean
     */
    var _play                = false;
    /**
     * Array contenente il titolo degli album da escludere
     * 
     * @type Array
     */
    var _exclude              = null;
    
    var __this               = null;
    
    
    var gallery = "<div id='gioiagallery'>"+
            "<div class='title'></div>"+
            
            "<div class='menu'></div>"+

            "<div class='images'></div>"+

            "<div class='commands'>"+
                "<div class='prev'></div>"+
                "<div class='next'></div>"+
            "</div>"+
            
            "<div class='info'>"+
                "<span class='count'></span>/<span class='total'></span>"+
            "</div>";

            "<div class='thumbnail'>"+
            "</div>"+
          "</div>";
    
    /*==================================================
     * ACCEDO A PICASA PER OTTENERE LE IMMAGINI VOLUTE
     =================================================*/
    function picasa(username, album, settings, gallery, _this, pos){
        var protocol            = document.location.protocol == 'http:' ? 'http:' : 'https:';
        var start               = (pos==0)?(settings.start<0)?0:settings.start:pos;
        var img_width           = 0;
        var imgContainer_width  = 0;
        
        
        __this                  = _this;
        _exclude                = settings.exclude;
        
        position                = start;
        fullscreen              = (settings.style.fullscreen==true)?true:false;
        
        //var album = settings.picasa.album;
        var url = protocol + '//picasaweb.google.com/data/feed/api/user/' + username + '/album/' + album + '?kind=photo&alt=json';
        
        $.ajax({
            dataType : 'json',
            url      : url,
            data     : 'callback=?',
            async    : false
        }).done(function (json){
            //Creo la photogallery
            $(_this).replaceWith(gallery);
            
            $("#gioiagallery .title").text(json.feed.title.$t);
            
            //Immagini
            for(i = 0; i < json.feed.entry.length; i++) {
                var summary = json.feed.entry[i].summary.$t;
                var img_src = json.feed.entry[i].content.src.split('/');
                var img_filename = img_src.pop();
                var img_src = img_src.join('/');
                var screen_width = $(window).width();
                
                html =  "<div>"+
                            "<img "+
                            " src='"+
                            img_src+'/s'+img_filename+
                            "'"+
                            " />"+
                            "</div>";
                
                $(container_images).append(html);
            }
            size = i;
            
            $(container_image).hide();
            $(container_image+':nth-child('+(position+1)+')').show();
            $(container_image+':nth-child('+(position+1)+') img').addClass('this');

            
            //Aggiungo a video il numero dell'immagine visualizzata e il numero totale
            $(container_count).text(position+1);
            $(container_size).text(size);
            
            //Prev
            if(position==0){$(prev).hide();}
            //Next
            if(position==size-1){$(next).hide();}
            
            
            img_fullscreen(fullscreen);
            
            
            
            //Aggiunta del menu
            if(settings.style.menu == true){
                var element = "<div class='toggle'>"+
                        "<div></div>"+
                        "<div></div>"+
                        "<div></div>"+
                        "</div>"+

                        "<div class='menu'></div>";

                $(menu).append(element);
            }
            
            //Aggiunta degli album come voce di menu
            var url = protocol + '//picasaweb.google.com/data/feed/api/user/' + username + '?kind=album&access=public&alt=json';
            $.getJSON(url, 'callback=?', $.proxy(function(json){
                var cont = 0;//Contatore degli album
                
                for(var i = 0; i < json.feed.entry.length; i++) {
                    var album_title = json.feed.entry[i].title.$t;
                    var album       = json.feed.entry[i].title.$t.replace(/\'/g, "").replace(/\ /g, "").replace(/\-/g, "");
                    var album_link  = "callback=?";
                    
                    var img_src = json.feed.entry[i].media$group.media$content[0].url.split('/');
                    var img_filename = img_src.pop();
                    var img_src = img_src.join('/');
                    
                    var result = false;
                    
                    $.each(_exclude, function (i, el){
                        if(el == album_title){
                            result = true;
                        }
                    });
                    
                    //if(album_title!='Foto del profilo'){
                    if(result==false){
                        html = "<div class='row'>"+
                                    "<div class='album'>"+
                                        "<a href='"+album_link+"' data-action='click' data-album='"+album+"' >"+album_title+"</a>"+
                                    "</div>"+
                                "</div>";
                    
                        $(menu_menu).append(html);

                        img_fullscreen(fullscreen);
                        
                        cont ++;
                    }
                }
                
                if(cont == 0){
                    $(menu_menu).html("<b>Nessun album disponibile");
                }
                
                
                /*==========================
                 * EVENTI LEGATI ALL'ALBUM
                ==========================*/
                //CLICK PER VISUALIZZARE IL NUOVO ALBUM
                $('[data-action=\'click\']').click(function (event){
                    event.preventDefault();
                    
                    //Richiamo il nuovo album di picasa
                    getAlbum(username, $(this).attr('data-album'), settings, gallery);
                });
            }));
            
            if(settings.commands.playpause == true){
                var element = "<div class='playpause ";
                            if(_play){
                                element += 'pause';
                            }else{
                                element += 'play';
                            }
                    element += "'>";
                    element += "</div>";
                $(container_commands).append(element);
            }
            
            //Controllo se la photogallery parte in autoplay
            if(settings.commands.autoplay == true){
                autoplay(true);
            }
            
            /*===============================
             * EVENTI LEGATI ALLE IMMAGINI
            ===============================*/
            //PREV BUTTON
            $(prev).bind('click', function (){
                $(next).show();

                if(position != 0){
                    if(position == 1){
                        $(prev).hide();
                    }

                    position --;

                    $(container_image).hide();
                }
                
                $(container_count).text(position+1);
                $(container_image+':nth-child('+(position)+') img').removeClass('this');
                $(container_image+':nth-child('+(position+1)+') img').addClass('this');
                $(container_image+':nth-child('+(position+1)+')').show();
                
                img_fullscreen(fullscreen);
            });
            
            //NEXT BUTTON
            $(next).bind('click', function (){
                $(prev).show();

                if(position != size-1){
                    if(position == size-2){
                        $(next).hide();
                    }

                    position ++;

                    $(container_image).hide();
                }
                
                $(container_count).text(position+1);
                $(container_image+':nth-child('+(position)+') img').removeClass('this');
                $(container_image+':nth-child('+(position+1)+') img').addClass('this');
                $(container_image+':nth-child('+(position+1)+')').show();
                
                img_fullscreen(fullscreen);
            });
            //PLAY
            $(container_playpause).bind('click', function (){
                if($(this).hasClass('play')){
                    $(this).removeClass('play').addClass('pause');
                    
                    autoplay(true);
                }else{
                    if($(this).hasClass('pause')){
                        $(this).removeClass('pause').addClass('play');
                        
                        autoplay(false);
                    }
                }
            });
            /*===============================
             * EVENTI LEGATI ALLE IMMAGINI
            ===============================*/
            
            //MENU
            $(menu_toggle).bind('click', function (){
                $(menu_menu).toggle();
            });
        }).fail(function (){
            alert('Impossibile aprire l\'album selezionato.')
        });
    }
    
    /*########################################
     * FUNZIONI
    ########################################*/
    
    /*=========================================
     * AVVIARE E VISUALIZZARE IL NUOVO ALBUM
    =========================================*/
    function getAlbum(username, album, settings, gallery){
        size = 0;
        
        picasa(username, album, settings, gallery, "#gioiagallery");
    }
    
    
    function img_fullscreen(fullscreen){
        if(fullscreen==true){
            var maxWidth  = $(container).width()*50/100;
            var maxheight = $(container).height()*50/100;
            var ratio     = 0;
            var width     = $("#gioiagallery .images img.this").width();
            var height    = $("#gioiagallery .images img.this").height();
            
            if($("#gioiagallery .images img.this").width() > $("#gioiagallery .images img.this").height()){
                ratio = (maxWidth/width);
                
                $("#gioiagallery .images img.this").css("width", width*ratio);
            }else{
                ratio = (maxheight/height);
                
                $("#gioiagallery .images img.this").css("height", height*ratio);
            }
            
            var container_images_width = $(container_images).width();
            var container_images_height = $(container_images).height();
            var top  = 0;
            var left = 0;
            
            container_img_width_this  = $("#gioiagallery .images img.this").width();
            container_img_height_this = $("#gioiagallery .images img.this").height();
            left = (container_images_width-container_img_width_this)/2;
            top  = (container_images_height-container_img_height_this)/2;

            $("#gioiagallery .images img.this").css({
                'margin-left' : left,
                'margin-top'  : top
            });
        }
    }
    
    /*//////////////////////////
     * FUNZIONI DEI CSS
    /////////////////////////*/
    /*===========================================
     * Dimensioni
     * 
     * @param int width
     * Larghezza
     * @param int height
     * Altezza
    =============================================*/
    function sizes(width, height){
        $('img', container_images).css({
            //width : ($(this).width()<$(container_images))?'2px':'100px'
            width : ($(this).width()>$(container_image).width())?($(this).height()<$(container_image).height())?'100px':(($(container_image).height())-10):'5px'
            /*width  : '100%',
            height : '100%'*/
        });
    }
    /*===========================================
     * Colori
     * 
     * @param string bgColor
     * Colore di sfondo
     * @param string color
     * Colore del font
    ===========================================*/
    function colors(bgColor, color){
        //Colori
        $(container).css({
            'background-color'  : bgColor,
            'color'             : color
        });
        $(container_count).css({
            'background-color'  : bgColor,
            'color'             : color
        });
    }
    /*===========================================
     * Ombre
     * 
     * @param string h
     * Posizione orizzontale dell'ombra
     * @param string v
     * Posizione verticale dell'ombra
     * @param string color
     * Colore dell'ombra
     * @param string spread
     * Valore dello spread
     * @param string blur
     * Valore del blur
    ===========================================*/
    function shadows(h, v, color, spread, blur){
        $('img', container_images).css({
            'box-shadow' : '0px 0px 5px 5px red'
        });
    }
    /*////////////////////////////////
     * FINE DELLE FUNZIONI DEI CSS
    ////////////////////////////////*/
    
    
    
    /*///////////////////////////////////////////
     * FUNZIONI PER L'USO DEI COMANDI
    //////////////////////////////////////////*/
    function playpause(){
        
    }
    function autoplay(b){
        if(b == true){
            _play = true;
            
            //Pulsante next
            if(position==size-2) $(next).hide();
            else $(next).show();
            //Pulsante prev
            if(position==size-1) $(prev).hide();
            else $(prev).show();
            
            //Azzeramento contatore delle posizioni
            if(position==size-1){
                position = 0;
            }else{
                position ++;
            }
            
            //position ++;
            
            
            $(container_play).removeClass('play').addClass('pause');
            
            $(container_count).text(position+1);
            $(container_image+':nth-child('+(position)+') img').removeClass('this');
            $(container_image+':nth-child('+(position)+')').fadeOut();
            $(container_image+':nth-child('+(position+1)+')').fadeIn();
            $(container_image+':nth-child('+(position+1)+') img').addClass('this');
            
            time = setTimeout(function (){
                autoplay(b);
            }, 6000);
            
            img_fullscreen(true);
        }else{
            _play = false;
            
            $(container_pause).removeClass('pause').addClass('play');
            
            clearTimeout(time);
        }
    }
    /*///////////////////////////////////////////
     * FINE FUNZIONI PER L'USO DEI COMANDI
    //////////////////////////////////////////*/
    
    /*#############################
     * FINE DELLE FUNZIONI
    #############################*/
    
    
    
    
    /*##############################
     * PLUGIN
    ##############################*/
    $.fn.photogallery = function( options ) {
        //Parametri di configurazione del plugin di default
        var defaults = {
            style : {
                bgColor : 'rgba(0, 0, 0, .9)',
                color   : 'white',
                size    : {
                    width  : '60%',
                    height : 'auto'
                }
            },
            position  : 'center',
            thumbnail : {
                show     : false,
                position : 'center',
                name     : 'thumbnail'
            },
            shadow      : {
                color   : 'red',
                h       : '0',
                v       : '0',
                spread  : '10px',
                blur    : '10px'
            }
        };
        var settings = $.extend({}, defaults, options );
        
        var html  = null;
        
        
        if(settings.type=='picasa'){
            //Restituisco le immagini
            picasa(settings.picasa.username, settings.picasa.album, settings, gallery, this, 0);
            
            //Ridimensionamento della photogallery dovuto alle variazioni delle dimensioni della pagina
            if(settings.style.fullscreen == true){
                $( window ).resize(function() {
                    var screen_width = $(window).width();
                    var screen_height = $(window).height();
                    
                    if(screen_width>800){
                        picasa(settings.picasa.username, settings.picasa.album, settings, gallery, "#gioiagallery", position);
                    }
                });
            }
        }
    };
})( jQuery );